# -*- coding: utf-8 -*-

import json
import time
from datetime import datetime as dt

from dateutil import parser

from analysis.games.es import emit_game_order
from common import orm
from common.lottery import METIS_GAME_TYPE
from common.platform.common.base import AbstractHandler
from common.platform.common.model import PLATFORM_TYPE
from common.platform.metis import db as metis_db
from common.platform.metis import metis_api
from common.utils import exceptions as err
from common.utils import track_logging, tracker
from common.utils import tz
from common.utils.types import Enum
from common.utils.currency import convert_fen_to_yuan, convert_yuan_to_fen
from common.utils.tz import (to_ts)

_LOGGER = track_logging.getLogger(__name__)


METIS_IS_BANKER_ENUM = Enum({
    "IS_NOT_BANKER": (1L, u'非庄家'),
    "IS_BANKER": (2L, u'庄家')
})


def _track_metis(item, invalid_amount, log):
    extend = json.loads(item['memo'])
    is_banker = True if extend['is_banker'] == METIS_IS_BANKER_ENUM.IS_BANKER else False
    user_bank_total_bet = 0
    if is_banker:
        section_bet_amount = extend['section_bet_money']
        _LOGGER.info('6666 %s', section_bet_amount)
        for bet_amount in section_bet_amount:
            _LOGGER.info('66666 %s', bet_amount)
            user_bank_total_bet += bet_amount
    _LOGGER.info('6666 %s', user_bank_total_bet)
    user_bank_bet_result = extend["total_bet_result"] if is_banker else 0
    tracker.track_metis(int(item['user_id']), item['game_id'], float(item['bet_amount']),
                        float(item['bet_result']), invalid_amount, log['create_time'],
                        is_banker, user_bank_total_bet, user_bank_bet_result)


def add_bet_logs_by_game(game_id):
    """
    定时游戏内注单写入mysql(cron job)
    """
    ticket_id = metis_db.get_ticketid_for_betlogs(game_id)
    _LOGGER.info('metis ticket_id: %s', ticket_id)
    while True:
        status, data = metis_api.query_betlogs_by_id(ticket_id, game_id, page=1, size=100)
        items = data['pageData']
        if items:
            try:
                for item in items:
                    ticket_id = item['id']
                    game_id = item['game_id']
                    if game_id == METIS_GAME_TYPE.FUNK_MONKEY:
                        log = metis_db.add_bet_logs(item)
                    else:
                        log = metis_db.add_bet_logs(item)
                        metis_db.cretate_game_term(item)
                        metis_db.cretate_game_part(item)
                    orm.session.commit()

                    invalid_amount = 0
                    if log['both_press']:
                        d = json.loads(item['memo'])
                        if log['game_id'] == METIS_GAME_TYPE.SUPER_SIX:
                            invalid_amount = 2 * min(d['section_bet_money'][3], d['section_bet_money'][5])
                        elif log['game_id'] == METIS_GAME_TYPE.DRAGON_TIGER:
                            invalid_amount = 2 * min(d['section_bet_money'][0], d['section_bet_money'][2])
                        elif log['game_id'] == METIS_GAME_TYPE.GOLD_SHARK:
                            invalid_amount = 2 * min(d['section_bet_money'][10], d['section_bet_money'][11])

                    emit_game_order(int(item['user_id']), PLATFORM_TYPE.METIS, item['game_id'], ticket_id,
                                    convert_yuan_to_fen(item['bet_amount']),
                                    convert_yuan_to_fen(item['bet_result']),
                                    dt.strptime(log['create_time'], "%Y-%m-%d %H:%M:%S"))
                    # track metis data here
                    _track_metis(item, invalid_amount, log)

            except:
                orm.session.rollback()
                raise
            finally:
                orm.session.close()
        else:
            orm.session.close()
            time.sleep(10)


def get_history(user_id, start_date=None, end_date=None, page=0, size=30):
    try:
        if start_date:
            start_date = parser.parse(start_date)
            start_date = to_ts(tz.local_to_utc(start_date))
        if end_date:
            end_date = parser.parse(end_date)
            end_date = to_ts(tz.local_to_utc(end_date))

    except Exception:
        raise err.ParamError('date format error')

    resp = metis_db.get_bet_logs_by_user_id(user_id, start_date, end_date, page,
                                            size)
    return resp


def set_pool(game_id, control_rate, control_pool):
    status = False
    if control_rate:
        status, data = metis_api.set_pool(game_id, control_rate=control_rate)
    elif control_pool:
        status, data = metis_api.set_pool(game_id, control_pool=control_pool)
    if status:
        now_rate, now_pool = data['pool_refund'], data['pool_money']
        resp = metis_db.add_pool(game_id, control_rate, control_pool,
                                 now_rate, now_pool)
        return resp
    raise err.ServerError(u'metis api error')


class MetisHandler(AbstractHandler):
    def get_platform_code(self):
        return PLATFORM_TYPE.METIS

    def shutdown(self):
        return False

    def available(self, user_id, **kwargs):
        if metis_db.is_over_daily_bet(user_id):
            raise err.ServerError(u'投注过多，请明日再来')
        if metis_db.is_pass_user(user_id):
            raise err.ServerError(u'游戏维护中，请稍后重试')
        if metis_db.is_black_user(user_id):
            raise err.ServerError(u'游戏维护中，请稍后重试')
        # if kwargs.get('game_id') and int(kwargs.get('game_id')) == METIS_GAME_TYPE.SUPER_BULL:
        #     raise err.ServerError(u'游戏维护中，请稍后重试')
        metis_api.query_balance(user_id)
        return True

    def check_trans_existed(self, ref_id):
        status, data = metis_api.query_ticket(ref_id)
        assert status and 'is_exists' in data
        return data['is_exists']

    def calculate_accumulated_win_amount(self, user_id, start_time, end_time):
        return metis_db.calculate_accumulated_win_amount(user_id, start_time, end_time)

    def query_balance_and_frozen_status(self, user_id):
        status, data = metis_api.query_balance(user_id)
        if not status:
            return 0, True
        balance = convert_yuan_to_fen(data['current_balance']) if data else 0
        if balance <= 0:
            return 0, True
        return balance, False

    def login_third(self, user_id, amount, ref_id, **params):
        status, data = metis_api.launch(user_id, user_name=params['user_name'], game_id=params['game_id'],
                                        ref_id=ref_id, amount=str(convert_fen_to_yuan(amount)), token=params['token'])
        if status:
            return data
        else:
            raise err.ServerError(u'登入游戏失败，请稍候重试')

    def logout_third(self, user_id, amount, ref_id, *params):
        status, data = metis_api.withdraw(user_id, ref_id, str(convert_fen_to_yuan(amount)))
        return status


handler = MetisHandler()
